<template>
  <div id="userview">
    <div class="user-header">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-form :inline="true" :model="formInline">
        <el-form-item label="请输入">
          <el-input
            placeholder="请输入用户名"
            v-model="formInline.keywords"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          v-for="col in tableColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width ? col.width : 125"
        >
          <template #default="scope" v-if="col.prop === 'sex'">
            <span>{{ scope.row.sex === 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleClick(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        size="small"
        :total="config.total"
        @current-change="handleChange"
        class="pager"
      />
      <el-dialog
        v-model="dialogVisible"
        :title="action == 'add' ? '新增用户' : '编辑用户'"
        width="35%"
        :before-close="handleClose"
      >
        <!--需要注意的是设置了:inline="true"，
		会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
		在css进行处理-->
        <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formUser.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input
                  v-model.number="formUser.age"
                  placeholder="请输入年龄"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item class="select-clearn" label="性别" prop="sex">
                <el-select v-model="formUser.sex" placeholder="请选择">
                  <el-option label="男" value="1" />
                  <el-option label="女" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birth">
                <el-date-picker
                  v-model="formUser.birth"
                  type="date"
                  placeholder="请输入"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="地址" prop="addr">
              <el-input v-model="formUser.addr" placeholder="请输入地址" />
            </el-form-item>
          </el-row>
          <el-row style="justify-content: flex-end">
            <el-form-item>
              <el-button type="primary" @click="handleCancel()">取消</el-button>
              <el-button type="primary" @click="onSubmit()">确定</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang='ts'>
import api from "@/api/api";
import "element-plus/dist/index.css";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";

const { proxy } = getCurrentInstance() as any;

const addUser = () => {
  console.log("新增用户");
};
const config = reactive({
  name: "",
  total: 0,
  page: 1,
});
const formInline = reactive({
  keywords: "",
});

const handleSearch = () => {
  console.log("搜索", formInline.keywords);
  config.name = formInline.keywords;
  getUserDataFn();
};
const handleClick = (val: any) => {
  action.value = "edit";
  dialogVisible.value = true;
  nextTick(() => {
    Object.assign(formUser,{...val,sex:""+val.sex});
  });
};
const tableColumns = [
  { prop: "name", label: "姓名" },
  { prop: "sex", label: "性别" },
  { prop: "age", label: "年龄" },
  { prop: "birth", label: "出生年月", width: 200 },
  { prop: "addr", label: "地址", width: 600 },
];
const tableData = ref([]);

const getUserDataFn = async () => {
  const res = await api.getUserData(config);
  console.log(res);
  tableData.value = res.data.list;
  config.total = res.data.count;
};
const handleChange = (page: number) => {
  config.page = page;
  getUserDataFn();
};

const handleDelete = (val: any) => {
  console.log("delete clicked", val);
  ElMessageBox.confirm("确定要删除吗？").then(async () => {
    const res: any = await api.deleteUser({ id: val.id });
    if (res.code === 200) {
      ElMessage.success({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
      getUserDataFn();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  });
};

//控制对话框是否显示
const dialogVisible = ref(false);

//新增和编辑共用一个窗口，所以通过设置action区分
const action = ref("add");

interface UserForm {
  id?: string;
  name: string;
  age: number | string;
  sex: string;
  birth: string | Date;
  addr: string;
}

const formUser = reactive<UserForm>({
  name: "",
  age: "",
  sex: "",
  birth: "",
  addr: "",
});
//表单校验规则
const rules = reactive({
  name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  age: [
    { required: true, message: "年龄是必填项", trigger: "blur" },
    { type: "number", message: "年龄必须是数字" },
  ],
  sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
  birth: [{ required: true, message: "出生日期是必选项" }],
  addr: [{ required: true, message: "地址是必填项" }],
});

//这个方法之前定义过
const handleAdd = () => {
  action.value = "add";
  //打开对话窗
  dialogVisible.value = true;
  nextTick(() => {
    proxy.$refs["userForm"].resetFields();
  });
};

//对话框右上角的关闭事件
const handleClose = () => {
  //获取到表单dom，执行resetFields重置表单
  proxy.$refs["userForm"].resetFields();
  //关闭对话框
  dialogVisible.value = false;
};

//对话框右下角的取消事件
const handleCancel = () => {
  proxy.$refs["userForm"].resetFields();
  dialogVisible.value = false;
};
//格式化日期，格式化为：1997-01-02这种
const timeFormat = (time: string | Date) => {
  var date = new Date(time);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  function add(m: number) {
    return m < 10 ? "0" + m : m;
  }
  return year + "-" + add(month) + "-" + add(day);
};

const onSubmit = () => {
  //执行userForm表单的validate进行规则校验，传入一个回调函数，回调函数会接受到一个是否校验通过的变量
  proxy.$refs["userForm"].validate(async (valid: boolean) => {
    //如果校验成功
    if (valid) {
      //res用于接收添加用户或者编辑用户接口的返回值
      let res: any = null;
      //这里无论是新增或者是编辑，我们都要对这个日期进行一个格式化
      //如果不是1997-01-02这种格式，使用timeFormat方法进行格式化
      if (formUser.birth) {
        formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(String(formUser.birth))
          ? formUser.birth
          : timeFormat(formUser.birth);
      }
      //如果当前的操作是新增，则调用新增接口
      if (action.value == "add") {
        res = await api.addUser(formUser);
      } else if (action.value == "edit") {
        res = await proxy.$api.updateUser(formUser);
      }
      //如果接口调用成功
      if (res) {
        //关闭对话框，重置表单，重新请求用户数据
        dialogVisible.value = false;
        proxy.$refs["userForm"].resetFields();
        ElMessage({
          showClose: true,
          message: "操作成功",
          type: "success",
        });
        getUserDataFn();
      }

      //如果校验失败
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的内容",
        type: "error",
      });
    }
  });
};

onMounted(() => {
  getUserDataFn();
});
</script>

<style scoped>
#userview {
}
.user-header {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.el-table {
  height: 100%;
}
.table {
  position: relative;
  min-height: 500px;
  padding-bottom: 50px;
}
.table .pager {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 10px;
  margin: 0 auto;
  display: flex;
  justify-content: right;
}
.select-clearn {
  display: flex;
}
</style>